//
//  ChargeController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/6/10.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import MJExtension
import SwiftyJSON

class ChargeController: CBBaseViewController {

    //余额
    @IBOutlet weak var lblMoney: UILabel!
    
    @IBOutlet weak var tfMoney: UITextField!
    
    @IBOutlet weak var lblBank: UILabel!
    
    @IBOutlet weak var tfBankCard: UITextField!
    
    @IBOutlet weak var tbBank: UITableView!
    
    @IBOutlet weak var nsTbBankHeight: NSLayoutConstraint!
    
    
    @IBOutlet weak var btnCharge: UIButton!
    
    @IBOutlet weak var ivUploadImage: UIImageView!
    
    var selectImage:Variable<UIImage?> = Variable(nil)
    
    @IBOutlet weak var ivCancel: UIImageView!
    
    
    weak var userModel:Variable<UserModel?>?
    let CELL_ID = "TB_BANK_CELL_ID"
    var arrBank:[String] = [String]()
    var arrSKBankInfo:[SKBankInfo] = [SKBankInfo]()
    weak var updateUserInfo:Variable<Bool>?
    
    @objc func clearImageSelect() {
        self.selectImage.value = nil
        self.ivUploadImage.image = UIImage(named: "add-photo")
        self.ivCancel.isHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我要充值"
        
        ivCancel.superview?.bringSubview(toFront: ivCancel)
        ivCancel.isHidden =  true
        ivCancel.addTapGesture(target: self, selector: #selector(clearImageSelect))
        
        //用户数据发生变化马上刷新界面
        userModel?.asObservable()
            .subscribe(onNext: { [weak self] _ in
                self?.flushView()
            }).disposed(by: disposeBag)
        
        
        SVProgressHUD.show()
        var count = 2
        let blkDismiss = {
            count -= 1
            if count == 0 {
                SVProgressHUD.dismiss()
            }
        }
        //读取银行卡信息
        NetworkTool.requestData(url: ActionURL.GET_BANK_LIST, param: nil)
            .map { (json) -> [String]? in
                return json["rows"].arrayObject as? [String]
            }.catchErrorJustReturn(nil)
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: { [weak self] opBankArr in
                blkDismiss()
                self?.arrBank = opBankArr ?? [String]()
            }).disposed(by: disposeBag)
        
        
        //读取收款银行卡信息
        NetworkTool.requestData(url: ActionURL.GET_SK_BANK, param: ["uid":MainTools.shared.userModel?.uid ?? ""])
            .map { (json) -> [SKBankInfo]? in
                return SKBankInfo.mj_objectArray(withKeyValuesArray: json["rows"].dictionaryValue["data"]?.arrayObject) as? [SKBankInfo]
            }.catchErrorJustReturn(nil)
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: { [weak self] opSKBankArr in
                blkDismiss()
                self?.arrSKBankInfo = opSKBankArr ?? [SKBankInfo]()
                self?.arrSKBankInfo.first?.isSelect = true
                let rowHt = (self?.arrSKBankInfo.count ?? 0).cg * 58
                self?.nsTbBankHeight.constant = rowHt
                self?.tbBank.reloadData()
            }).disposed(by: disposeBag)
        
        //监听银行卡输入框
        tfBankCard.rx.controlEvent(UIControlEvents.editingChanged).asDriver()
            .drive(onNext:{ [unowned self] _ in
                let strBankcard = (self.tfBankCard.text ?? "").trim
                self.tfBankCard.text = strBankcard.bankcardFormat
            }).disposed(by: disposeBag)
        
        //整合输入流
        let combinInput = Observable.combineLatest(tfMoney.rx.observe(String.self, "text").asObservable(), lblBank.rx.observe(String.self, "text").asObservable(), tfBankCard.rx.observe(String.self, "text").asObservable(), selectImage.asObservable()) { return (money:$0 ?? "", bank:$1 ?? "", bankCard:($2 ?? "").trim, image:$3) }
            .share(replay:1)
        
        combinInput.map { input -> Bool in
                let validMoney = !input.money.isEmpty && input.money != "0"
                let validBank = !input.bank.isEmpty
                let validBankCard = !input.bankCard.isEmpty
                let validImage = (input.image != nil)
                return validMoney && validBank && validBankCard && validImage
            }.subscribe(onNext: { [weak self] isValid in
                self?.btnCharge.isEnabled = isValid
                self?.btnCharge.alpha = isValid ? 1.0 : 0.5
            }).disposed(by: disposeBag)
        
        //提交充值
        btnCharge.rx.tap.asObservable()
            .withLatestFrom(combinInput)
            .flatMapLatest { [unowned self] input -> Observable<Bool> in
                self.view.endEditing(true)
                
                if (MainTools.shared.userModel?.idcard.isEmpty ?? true) == true {
                    let vwAlert = UIAlertView(title: "提示", message: "为了您的资金安全，请填写身份证信息后，才能完成充值。", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
                    vwAlert.show()
                    return Observable.just(false)
                }
                
                SVProgressHUD.show()
                var for_bank = ""
                var for_card = ""
                for model in self.arrSKBankInfo {
                    if model.isSelect {
                        for_bank = model.name
                        for_card = model.card
                        break
                    }
                }
                
                return NetworkTool.requestData(url: ActionURL.UPLOAD_IMAGE, param: ["img": MainTools.converImageToBase64String(myImage: input.image)]).flatMap({ (json) -> Observable<JSON> in
                    return NetworkTool.requestData(url: ActionURL.CHARGE_OR_WITHDRAW, param: ["uid":self.userModel?.value?.uid ?? "","bank":input.bank,"card":input.bankCard,"type":"3","amount":input.money,"for_bank":for_bank,"for_card":for_card,"img":json["url"].stringValue])
                }).map({ (json) in
                    return true
                }).catchErrorJustReturn(false)
            }.subscribe(onNext:{ [weak self] isSuccess in
                SVProgressHUD.dismiss()
                if isSuccess {
                    self?.clearInput()
                    let vwTips = (Bundle.main.loadNibNamed("ChargeWithdrawTipsView", owner: nil, options: nil)?.first as? ChargeWithdrawTipsView) ?? ChargeWithdrawTipsView()
                    vwTips.show(isSuccess: isSuccess, type: 0, tipsFailInfo: "")
                }
            })
            .disposed(by: disposeBag)
        
    }
    
    func clearInput() {
        tfMoney.text = ""
    }
    
    override func setupRightBtnAction() {
        self.view.endEditing(true)
        let btnDetail = UIButton(text: "明细", color: .white, fontSize: 15.wr)
        btnDetail.cb_size = CGSize(width: 30, height: 30)
        btnDetail.rx.tap
            .subscribe(onNext:{ [weak self] _ in
                let detailVc = FundRecordController()
                self?.navigationController?.pushViewController(detailVc, animated: true)
            }).disposed(by: disposeBag)
        let rightBarButtonItem:UIBarButtonItem =
            UIBarButtonItem(customView: btnDetail)
        rightBarButtonItem.tintColor = .white
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
    }
    
    //刷新视图
    func flushView() {
        lblMoney.text = userModel?.value?.balance ?? "0.0"
    }
    
    @IBAction func selectBank(_ sender: UITapGestureRecognizer) {
        self.view.endEditing(true)
        let vwPick = CBPickView(arrData: self.arrBank, strTitle: "请选择充值银行") { [weak self] (strSelectBank) in
            self?.lblBank.text = strSelectBank
        }
        vwPick.show(strSelectValue: self.lblBank.text ?? "")
    }
    
    
    @IBAction func showUploadImage(_ sender: UITapGestureRecognizer) {
        if let image = selectImage.value {
            let browser = SKPhotoBrowser(photos: [SKPhoto.photoWithImage(image)])
            browser.initializePageIndex(0)
            present(browser, animated: true, completion: {})
        } else {
            var sheet:UIActionSheet
            if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)){
                sheet = UIActionSheet(title: "选择", delegate: self, cancelButtonTitle: nil, destructiveButtonTitle: "从相册中选择", otherButtonTitles: "拍照", "取消")
            }else{
                sheet = UIActionSheet(title: "选择", delegate: self, cancelButtonTitle: nil , destructiveButtonTitle: "从相册中选择", otherButtonTitles: "取消")
            }
            sheet.tag = 255
            sheet.show(in: self.view)
        }
        
    }
    
}

extension ChargeController: UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //选择图片
    func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
        if(actionSheet.tag == 255){
            var soureceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.photoLibrary
            if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) {
                switch(buttonIndex) {
                    case 2://取消
                        return
                    case 1://相机
                        soureceType = UIImagePickerControllerSourceType.camera
                        break
                    case 0: //相册
                        soureceType = UIImagePickerControllerSourceType.photoLibrary
                        break
                    default:
                        return
                }
            } else {
                if(buttonIndex == 1){
                    return
                }else{
                    soureceType = UIImagePickerControllerSourceType.savedPhotosAlbum
                }
            }
            
            if soureceType == UIImagePickerControllerSourceType.camera && !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
                UIAlertView.showInfoMessage("请在设置-->隐私-->相机，中开启本应用的相机访问权限！")
                return
            } else if soureceType == UIImagePickerControllerSourceType.photoLibrary && !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
                UIAlertView.showInfoMessage("请在设置-->隐私-->相册，中开启本应用的相册访问权限！")
                return
            }
            
            let imagePickerController:UIImagePickerController = UIImagePickerController()
            imagePickerController.delegate = self
//            imagePickerController.allowsEditing = false
            imagePickerController.sourceType = soureceType
            self.present(imagePickerController, animated: true, completion: nil)
        }
    }

    //image picker delegte
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        picker.dismiss(animated: true, completion: { () -> Void in
        })
        
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            self.selectImage.value = image
            self.ivUploadImage.image = image
            self.ivCancel.isHidden = false
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }
    
}

extension ChargeController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrSKBankInfo.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID, for: indexPath)
        let vwContent:UIView = cell.viewWithTag(1) ?? UIView()
        let lblBank:UILabel = cell.viewWithTag(2) as? UILabel ?? UILabel()
        let lblFenBank:UILabel = cell.viewWithTag(3) as? UILabel ?? UILabel()
        let lblBankCard:UILabel = cell.viewWithTag(4) as? UILabel ?? UILabel()
        let ivGou:UIImageView = cell.viewWithTag(5) as? UIImageView ?? UIImageView()
        
        let model = arrSKBankInfo[indexPath.row]
        lblBank.text = model.name
        lblFenBank.text = "开户行：\(model.open_bank)"
        lblBankCard.text = model.card.bankcardFormat
        ivGou.isHidden = !model.isSelect
        vwContent.borderWidth = model.isSelect ? 1.0 : 0.0
        
        //屏幕点击释放
        let viewTap = UITapGestureRecognizer()
        viewTap.rx.event.subscribe(onNext:{ [unowned self] _ in
            for tpModel in self.arrSKBankInfo {
                tpModel.isSelect = false
            }
            model.isSelect = true
            self.tbBank.reloadData()
        }).disposed(by: disposeBag)
        vwContent.addGestureRecognizer(viewTap)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        for model in arrSKBankInfo {
            model.isSelect = false
        }
        let model = arrSKBankInfo[indexPath.row]
        model.isSelect = true
        self.tbBank.reloadData()
    }
    
}

extension ChargeController : UIAlertViewDelegate {
    
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
        if buttonIndex == 1 {  //确认
            let vc = MainTools.initSbVc(sbName: "My", AnyClass: IdCardController.self)
            vc.updateUserInfo = updateUserInfo
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}

